package com.zz.zjc.service;

import com.zz.zjc.dao.UserDao;
import com.zz.zjc.exception.MessageException;
import com.zz.zjc.model.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService  {

    @Resource
    UserDao userDao;
    @Resource
    VerificationService verificationService;

    public User login(String name, String pass) {
        User user= userDao.login(name,pass);
        if (user!=null){
            //移除隐私信息
            user.setPass(null);
        }
        return user;
    }

    public User get(Integer userId) {
        return userDao.selectByPrimaryKey(userId);
    }


    public int register(Integer accountType, String account, String pass,String code) {
        List<User> userList =userDao.queryAccount(account);
        if(userList.size()>0){
            //账号已经注册
            throw new MessageException("账号已经注册");
        }
        //检验验证码
        verificationService.checkCode(0,account,code);
        String name="";
        String tel="";
        String mail="";
        String head="img/login_head.png";
        if (accountType == 0) {
            mail=account;
            name="用户"+account.substring(0,2);
        }else if (accountType == 1) {
            tel=account;
            name="用户"+account.substring(account.length()-4,account.length());
        }
        User user =new User();
        user.setName(name);
        user.setTel(tel);
        user.setMail(mail);
        user.setHead(head);
        user.setPass(pass);
        userDao.insertSelective(user);
        return 200;
    }

    public int resetPass(String account, String pass, String code) {
        List<User> userList =userDao.queryAccount(account);
        if(userList.size()==0){
            //账号不存在
            throw new MessageException("账号不存在");
        }
        //检验验证码
        verificationService.checkCode(1,account,code);
        //验证码正确，重置密码
        User user =new User();
        user.setId(userList.get(0).getId());
        user.setPass(pass);
        userDao.updateByPrimaryKeySelective(user);
        return 200;
    }

    public void update(User user) {
        userDao.updateByPrimaryKeySelective(user);
    }
}
